package com.miqtech.master.wyrecorder.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.annotations.LayoutId;
import com.miqtech.master.wyrecorder.annotations.Title;
import com.miqtech.master.wyrecorder.base.BaseAppCompatActivity;
import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.constants.Constants;
import com.miqtech.master.wyrecorder.entity.User;
import com.miqtech.master.wyrecorder.nim.NIMHelper;
import com.miqtech.master.wyrecorder.user.UserProxy;
import com.miqtech.master.wyrecorder.utils.DeviceUtils;
import com.miqtech.master.wyrecorder.utils.L;
import com.miqtech.master.wyrecorder.utils.Utils;
import com.miqtech.master.wyrecorder.widget.PhoneTextWatcher;
import com.miqtech.master.wyrecorder.widget.ResizeLayout;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by zhaosentao on 2016/8/22.
 */
@LayoutId(R.layout.activity_login)
@Title(title = "登录")
public class LoginActivity extends BaseAppCompatActivity implements TextWatcher, PhoneTextWatcher.ContextListener, UserProxy.OnUserChangeListener {
    public static boolean isHasLoginActivity = true;
    public static final int CODE_LOGIN_SUCCESS_REQUEST = 100;
    @BindView(R.id.loginRlPhone)
    RelativeLayout rlPhone;
    @BindView(R.id.loginEtPhone)
    EditText etPhone;
    @BindView(R.id.loginIvClearPhone)
    ImageView ivClearPhone;
    @BindView(R.id.loginRlPassword)
    RelativeLayout rlPassword;
    @BindView(R.id.loginEtPassword)
    EditText etPassword;
    @BindView(R.id.tvFastPhoneLogin)
    TextView tvFastPhoneLogin; //手机号码快捷登录
    @BindView(R.id.btnLogin)
    Button btnLogin;

    @BindView(R.id.svParent)
    LinearLayout svParent;
    @BindView(R.id.rlParent)
    ResizeLayout rlParent;
    @BindView(R.id.llSnckbar)
    LinearLayout llSnckbar;
    private String imputPhone;//输入的电话
    private String imputPassword;//输入的密码
    private PhoneTextWatcher watcher;

    private int[] locationXY = new int[2];
    private int commentPositionY = 0;
    private boolean isPasswordFormatRight = false;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        isHasLoginActivity = false;
        setHeaderTranslate();
        hideBack();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        watcher = new PhoneTextWatcher(etPhone, ivClearPhone, getResources().getString(R.string.please_imput_phone), this);
        etPhone.requestFocus();
        etPhone.addTextChangedListener(watcher);
        etPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && (!watcher.isFullPhone() || !etPhone.getText().toString().replaceAll("\\s*", "").matches(Constants.PHONE_FORMAT))) {
                    setLoginTipsVisible(true);
                } else {
                    setLoginTipsVisible(false);
                }
            }
        });
        etPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && etPassword.getText().toString().length() < 6) {
                    setCodeTipsVisible(true);
                } else {
                    setCodeTipsVisible(false);
                }
            }
        });
        etPassword.addTextChangedListener(this);
        loginIsClick(false);
        //防止获取的locationXY值为0
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                btnLogin.getLocationOnScreen(locationXY);
                commentPositionY = DeviceUtils.deviceHeight(LoginActivity.this) - (locationXY[1] + btnLogin.getHeight());
            }
        }, 100);
        rlParent.setOnKeyboardShowListener(new ResizeLayout.OnkeyboardShowListener() {
            @Override
            public void onKeyboardShow(int heightDiff) {
                rlParent.setPadding(0, -(heightDiff - commentPositionY), 0, 0);
            }

            @Override
            public void onKeyboardHide() {
                rlParent.setPadding(0, 0, 0, 0);
            }
        });

        UserProxy.addListener(this);
        L.e(TAG, "initViews ok");
    }

    /**
     * 设置登录错误提示 和手机输入框
     *
     * @param isVisible
     */
    private void setLoginTipsVisible(boolean isVisible) {
        if (isVisible) {
            showSnackBar(llSnckbar, getString(R.string.account_error_tips));
        }
        rlPhone.setBackgroundDrawable(getResources().getDrawable(isVisible == true ? R.drawable.format_error_shape_icon : R.color.transparent));
    }

    /**
     * 设置错误验证码提示 和验证码框
     *
     * @param isVisible
     */
    private void setCodeTipsVisible(boolean isVisible) {
        if (isVisible) {
            showSnackBar(llSnckbar, getString(R.string.password_error_tip));
        }
        rlPassword.setBackgroundDrawable(getResources().getDrawable(isVisible == true ? R.drawable.format_error_shape_icon : R.color.transparent));
    }

    /**
     * 清除焦点 并消失软键盘
     *
     * @param et
     */
    private void clearInputBg(EditText et) {
        ((ViewGroup) et.getParent()).setFocusable(true);
        ((ViewGroup) et.getParent()).setFocusableInTouchMode(true);
        ((ViewGroup) et.getParent()).requestFocus();
        Utils.hiddenKeyBoard(this);
    }

    /**
     * 登录按钮背景色和文字颜色
     *
     * @param isClick
     */
    private void loginIsClick(boolean isClick) {
        if (isClick) {
            btnLogin.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_login_btn_bg));
            btnLogin.setTextColor(getResources().getColor(R.color.white));
        } else {
            btnLogin.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_unlogin_btn_bg));
            btnLogin.setTextColor(getResources().getColor(R.color.bar_text_selected));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    @OnClick({R.id.btnLogin,
            R.id.tvFastPhoneLogin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvFastPhoneLogin:
                jumpToActivityForResult(FastLoginActivity.class, CODE_LOGIN_SUCCESS_REQUEST);
                break;
            case R.id.btnLogin://登录
                if (isPasswordFormatRight && watcher.isFullPhone()) {
                    goToLogin();
                } else {
                    if (etPhone.isFocused()) {
                        clearInputBg(etPhone);
                    } else if (etPassword.isFocused()) {
                        clearInputBg(etPassword);
                    }
                }
                break;

        }
    }

    private void goToLogin() {
        imputPhone = etPhone.getText().toString();
        imputPhone = imputPhone.replaceAll("\\s*", "");
        imputPassword = etPassword.getText().toString();

        if (!imputPhone.matches(Constants.PHONE_FORMAT)) {//校验手机号码
            showToast(getResources().getString(R.string.phone_format_is_not_correct));
            return;
        }
        NIMHelper.getInstance().logout();

        Map<String, String> map = new HashMap();
        map.put("username", imputPhone);
        map.put("source", "2");
        map.put("type", "1");
        map.put("password", imputPassword);
        sendHttpRequest(API.LOGIN, map);
    }

    @Override
    public void onSuccess(JSONObject object, String method) {
        super.onSuccess(object, method);
        switch (method) {
            case API.LOGIN:
                loginSuccess(object);
                jumpToActivity(MainActivity.class);
                break;

        }
    }

    @Override
    public void onError(String errMsg, String method) {
        super.onError(errMsg, method);
        showToast(getResources().getString(R.string.noNeteork));
    }

    @Override
    public void onFaild(JSONObject object, String method) {
        super.onFaild(object, method);
        try {
            switch (method) {
                case API.LOGIN:
                    if (object.has("result")) {
                        showToast(object.getString("result").toString());
                    } else {
                        showToast(getResources().getString(R.string.login_fail));
                    }
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (etPassword.isFocused() && etPassword.getText().length() >= 6) {
            isPasswordFormatRight = true;
            if (watcher.isFullPhone()) {
                loginIsClick(true);
            } else {
                loginIsClick(false);
            }
        } else {
            //输入正确的密码格式
            isPasswordFormatRight = false;
            loginIsClick(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 登录成功后
     *
     * @param object
     */
    private void loginSuccess(final JSONObject object) {
        try {
            User user = new Gson().fromJson(object.getString("object"), User.class);
			if(user != null)
			{
                UserProxy.setUser(user);
				NIMHelper.getInstance().login(user.getShouboAccid(),user.getId());
			}
            this.setResult(RESULT_OK);
            Utils.hiddenKeyBoard(this);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 100);
        } catch (JSONException e) {
            e.printStackTrace();
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isHasLoginActivity = true;
        UserProxy.removeListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_LOGIN_SUCCESS_REQUEST && resultCode == RESULT_OK) {
            finish();
        }
        if (data == null) {
            return;
        }
        if (requestCode == 10) {
            int registerOk = data.getIntExtra("register_ok", -1);
            if (registerOk == 1) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }


    @Override
    public void setValue(boolean isWholePhoneNum) {
        if (isWholePhoneNum && isPasswordFormatRight) {
            loginIsClick(true);
        } else {
            loginIsClick(false);
        }
    }

    @Override
    public void onUserChange(User user) {
        if (user != null) {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        moveTaskToBack(true);
    }
}